import Vue from "vue";
import App from "./App";
import router from "./router";
import store from "./store/";
import vueNcform from "@ncform/ncform";

import Element from "element-ui";
import "element-ui/lib/theme-chalk/index.css";
import ncformStdComps from "@ncform/ncform-theme-elementui";
import axios from "axios";

import MyCustomComp from "@/components/MyCustomComp"; // Your custom form widget
import MyCustomRule from "@/rules/MyCustomRule"; // Your custom rule

// 视频播放 vue-video-player
import VueVideoPlayer from "vue-video-player";
Vue.use(VueVideoPlayer);

Vue.use(Element);
Vue.use(vueNcform, {
  extComponents: Object.assign(ncformStdComps, {
    MyCustomComp
  }),
  extRules: [{
    myCustom: MyCustomRule
  }],
  lang: "" // you can try 'en' or 'zh-cn'
});
window.$http = Vue.prototype.$http = axios;

Vue.config.productionTip = false;

axios.defaults.withCredentials = true;

// 路由拦截, 切换路由强制取消上一各页面发起的请求
import axioStore from "./api/axioStore";

import store_ from "./store/index"


const LOGIN_PAGE_NAME = "login";

let Base64 = require("js-base64").Base64;

router.beforeEach((to, from, next) => {
  //进行路由拦截，路由切换时取消上个路由发出的请求
  axioStore.commit("clearToken");

  let isLogin = store.state.loginStatus;
  if (isLogin) {
    if (to.name === LOGIN_PAGE_NAME) {
      // 如果已登录，还想进入登录注册界面，则返回
      next({
        name: from.name
      })
    } else if (to.path == "/") {  //如果进入https信令测试页面
      store_.commit("CHANGEFIRSTHTTPSPAGEFLAG", {val:0});
      next()
    }else{
      next()
    }
  } else {
    // 如果未登录
    if (to.meta.requiresAuth) {
      next({
        name: LOGIN_PAGE_NAME
      })
    } else {
      next()
    }
  }
});

// 认证接口(HTTP Basic Authorization认证)
axios.interceptors.request.use(
  config => {
    if (sessionStorage.key("token") === null) { 
      config.headers.Authorization = `Basic ${Base64.encode(store.state.userInfo.userName + ":" + store.state.userInfo.password)}`;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

// 向除了认证接口（reqAuth）的其他接口的请求头中加入token：
axios.interceptors.request.use(
  config => {
    if (sessionStorage.key("token") !== null) {
      config.headers.Authorization = `Bearer ${JSON.parse(
        sessionStorage.getItem("token")
      )}`;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  }
);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount("#app");